package com.promise.jokerdream.ui.tower

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.promise.jokerdream.model.knight.KnightDreamInstanceModel
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.ui.components.PMDialog
import com.promise.jokerdream.ui.components.RoundCheckbox
import com.promise.jokerdream.ui.components.CheckboxOptionRow
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.database.entity.KnightDreamGameConfigEntity
import com.promise.jokerdream.config.game.KnightDreamPriority
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.repository.foldWithApiException
import kotlinx.coroutines.launch

/**
 * 江湖长梦对话框
 */
@Composable
fun KnightDreamDialog(
    show: Boolean,
    onDismiss: () -> Unit,
    onConfirm: (KnightDreamGameConfigEntity) -> Unit,
) {
    val context = LocalContext.current
    val userDataManager = remember { UserDataManager.getInstance(context) }
    
    // 江湖长梦相关状态
    var selectedPriority by remember { mutableStateOf("ADVENTURE") } // 优先级选择（String）
    var selectedDungeon by remember { mutableStateOf<KnightDreamInstanceModel?>(null) }
    
    // 保存配置的辅助函数
    fun savePriorityConfig(priority: String) {
        val currentAccount = userDataManager.getCurrentAccount()
        if (currentAccount != null) {
            val config = KnightDreamGameConfigEntity(
                userId = currentAccount.userId,
                enabledSetting = true,
                priority = priority,
                selectedDungeonId = selectedDungeon?.id ?: 0,
                challengeCount = 1
            )
            val updatedGameConfig = currentAccount.config.gameConfig.copy(
                knightDreamConfig = config
            )
            val updatedUserConfig = currentAccount.config.copy(
                gameConfig = updatedGameConfig
            )
            val updatedAccount = currentAccount.copy(config = updatedUserConfig)
            userDataManager.saveUserAccount(updatedAccount)
        }
    }
    
    // 副本列表状态
    var dungeonList by remember { mutableStateOf<List<KnightDreamInstanceModel>>(emptyList()) }
    var isLoadingDungeons by remember { mutableStateOf(false) }
    var gameApi by remember { mutableStateOf(GameApi()) }
    val scope = rememberCoroutineScope()
    
    // 读取用户配置 - 每次对话框显示时执行
    LaunchedEffect(show) {
        if (show) {
            val currentAccount = userDataManager.getCurrentAccount()
            val config = currentAccount?.config?.gameConfig?.knightDreamConfig
            if (config != null) {
                selectedPriority = config.priority
            }
        }
    }
    
    // 加载副本列表 - 每次对话框显示时都重新拉取数据
    LaunchedEffect(show) {
        if (show && dungeonList.isEmpty()) {
            isLoadingDungeons = true
            scope.launch {
                try {
                    val result = gameApi.queryKnightDream()
                    result.foldWithApiException(
                        onSuccess = { response ->
                            dungeonList = response.copyList.filter { it.status > 0 }
                            if (dungeonList.isNotEmpty()) {
                                selectedDungeon = dungeonList.first()
                            }
                        },
                        onFailure = { code, msg ->
                            // 失败
                        }
                    )
                } catch (e: Exception) {
                    // 处理错误
                } finally {
                    isLoadingDungeons = false
                }
            }
        }
    }

    PMDialog(
        show = show,
        title = "江湖长梦",
        confirmText = "开始执行",
        cancelText = "取消",
        confirmButtonColor = MaterialTheme.colorScheme.primary,
        onDismiss = onDismiss,
        onConfirm = {
            // 直接创建配置对象并确认，使用默认挑战次数
            val currentAccount = userDataManager.getCurrentAccount()
            val config = KnightDreamGameConfigEntity(
                userId = currentAccount?.userId ?: "",
                enabledSetting = true,
                priority = selectedPriority,
                selectedDungeonId = selectedDungeon?.id ?: 0,
                challengeCount = 9999
            )
            onConfirm(config)
        }
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(rememberScrollState())
        ) {
            
            // 优先级选择 - 左右布局
            Text(
                text = "优先级设置",
                fontSize = AppFontSizes.mediumBody,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                horizontalArrangement = Arrangement.SpaceEvenly
            ) {
                // 奇遇优先
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .weight(1f)
                        .clickable { 
                            selectedPriority = "ADVENTURE"
                            savePriorityConfig("ADVENTURE")
                        }
                        .padding(vertical = 8.dp)
                ) {
                    RoundCheckbox(
                        checked = selectedPriority == "ADVENTURE",
                        onCheckedChange = { 
                            if (it) {
                                selectedPriority = "ADVENTURE"
                                savePriorityConfig("ADVENTURE")
                            }
                        },
                        size = 18.dp
                    )
                    Spacer(modifier = Modifier.width(6.dp))
                    Text(
                        text = "奇遇优先",
                        fontSize = AppFontSizes.body,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                }
                
                // 战斗优先
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .weight(1f)
                        .clickable { 
                            selectedPriority = "BATTLE"
                            savePriorityConfig("BATTLE")
                        }
                        .padding(vertical = 8.dp)
                ) {
                    RoundCheckbox(
                        checked = selectedPriority == "BATTLE",
                        onCheckedChange = { 
                            if (it) {
                                selectedPriority = "BATTLE"
                                savePriorityConfig("BATTLE")
                            }
                        },
                        size = 18.dp
                    )
                    Spacer(modifier = Modifier.width(6.dp))
                    Text(
                        text = "战斗优先",
                        fontSize = AppFontSizes.body,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                }
            }
            
            // 副本选择
            Text(
                text = "副本选择",
                fontSize = AppFontSizes.mediumBody,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            // 副本选项列表 - 支持滑动，最多显示5行
            if (isLoadingDungeons) {
                Box(
                    modifier = Modifier
                        .height(100.dp)
                        .fillMaxWidth(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else {
                LazyColumn(
                    modifier = Modifier
                        .heightIn(max = 200.dp) // 最多显示5行的高度
                        .fillMaxWidth(),
                    verticalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    items(dungeonList) { dungeon ->
                        CheckboxOptionRow(
                            title = dungeon.name,
                            desc = dungeon.useDesc,
                            checked = selectedDungeon?.id == dungeon.id,
                            onCheckedChange = { 
                                if (it) selectedDungeon = dungeon
                            }
                        )
                    }
                }
            }
        }
    }
}

